<?php

class Application_Model_PaysDAO
{
	protected $_dbTable;

	public function setDbTable($dbTable)
	{
		if(is_string($dbTable))
		{
			$dbTable = new $dbTable();
		}
		if(!$dbTable instanceof Zend_Db_Table_Abstract)
		{
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
 
	public function getDbTable()
	{
		if(null === $this->_dbTable)
		{
			$this->setDbTable('Application_Model_DbTable_Pays');
		}
		return $this->_dbTable;
	}
	
	public function save(Default_Model_Pays $pays)
	{
		$data = array(
			'PAYNUM' => $pays->getPayNum(),
			'PAYNOM' => $pays->getPayNom(),
			'PAYNAT' => $pays->getPayNat(),
			'PAYADRDRAP' => $pays->getPayAdrDrap()
		);
 
		if (null === ($payNum = $pays->getPayNum()))
		{
			unset($data['PAYNUM']);
			$this->getDbTable()->insert($data);
        }
        else
        {
			$this->getDbTable()->update($data, array('PAYNUM = ?' => $payNum));
		}
	}
	
	public function find($payNum)
	{
		$pays = new Application_Model_Pays();

		$result = $this->getDbTable()->find($payNum);
		if(0 == count($result))
		{
			return null;
		}
		$row = $result->current();
		$pays->setPayNum($row->PAYNUM)
			 ->setPayNom($row->PAYNOM)
			 ->setPayNat($row->PAYNAT)
			 ->setPayAdrDrap($row->PAYADRDRAP);

		return $pays;
	}
	
	public function findAll()
	{
		$resultSet = $this->getDbTable()->fetchAll($this->getDbTable()->select()->from('pays',array('PAYNUM'))->order('PAYNOM ASC'));
		$entries = array();
		foreach($resultSet as $row)
		{
			$entries[] = $this->find((int)$row->PAYNUM);
		}
		return $entries;
	}
}